package com.dd.controller;

import com.dd.model.AQIData;
import com.dd.service.AQIDataService;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.collections.transformation.FilteredList;
import javafx.fxml.FXML;
import javafx.scene.control.Alert;
import javafx.scene.control.Alert.AlertType;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.scene.control.TextField;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.scene.control.ComboBox;
import java.util.List;

/*
AQIDataListController 是一个 JavaFX 控制器类，主要用于管理和展示 AQI（空气质量指数）数据列表。它的核心职责包括：
初始化和配置 TableView，将 AQI 数据的各个字段（如编号、反馈者、省、市、等级、日期、时间、网格员）映射到表格的每一列。
通过 AQIDataService 获取所有 AQI 数据，并支持数据的筛选和过滤（比如根据 AQI 等级、搜索关键词等）。
提供搜索和重置功能，允许用户根据输入的关键词和选择的 AQI 等级筛选表格中的数据。
提供查看详情功能，弹窗显示选中数据的详细信息。
提供刷新功能，重新加载和显示最新的 AQI 数据。
简单来说，这个类是“空气质量数据列表页面”的控制器，负责数据的加载、展示、筛选、详情查看等交互逻辑。
*/
public class AQIDataListController {
    @FXML private TableView<AQIData> aqiDataTable;
    @FXML private TableColumn<AQIData, String> idCol;
    @FXML private TableColumn<AQIData, String> reporterCol;
    @FXML private TableColumn<AQIData, String> provinceCol;
    @FXML private TableColumn<AQIData, String> cityCol;
    @FXML private TableColumn<AQIData, String> aqiLevelCol;
    @FXML private TableColumn<AQIData, String> dateCol;
    @FXML private TableColumn<AQIData, String> timeCol;
    @FXML private TableColumn<AQIData, String> gridWorkerCol;
    @FXML private TextField searchField;
    @FXML private ComboBox<String> aqiLevelComboBox;

    private final AQIDataService service = new AQIDataService();
    private ObservableList<AQIData> masterData;
    private FilteredList<AQIData> filteredData;

    @FXML
    public void initialize() {
        idCol.setCellValueFactory(new PropertyValueFactory<>("id"));
        reporterCol.setCellValueFactory(new PropertyValueFactory<>("reporter"));
        provinceCol.setCellValueFactory(new PropertyValueFactory<>("province"));
        cityCol.setCellValueFactory(new PropertyValueFactory<>("city"));
        aqiLevelCol.setCellValueFactory(new PropertyValueFactory<>("aqiLevel"));
        dateCol.setCellValueFactory(new PropertyValueFactory<>("date"));
        timeCol.setCellValueFactory(new PropertyValueFactory<>("time"));
        gridWorkerCol.setCellValueFactory(new PropertyValueFactory<>("gridWorker"));
        List<AQIData> data = service.getAllAQIData();
        masterData = FXCollections.observableArrayList(data);
        filteredData = new FilteredList<>(masterData, p -> true);
        aqiDataTable.setItems(filteredData);
        // 初始化 AQI 等级下拉框
        aqiLevelComboBox.getItems().clear();
        aqiLevelComboBox.getItems().add("全部");
        masterData.stream().map(AQIData::getAqiLevel).distinct().forEach(level -> {
            if (level != null && !level.isEmpty() && !aqiLevelComboBox.getItems().contains(level)) {
                aqiLevelComboBox.getItems().add(level);
            }
        });
        aqiLevelComboBox.getSelectionModel().selectFirst();
    }

    @FXML
    private void handleSearch() {
        String searchText = searchField.getText();
        String selectedLevel = aqiLevelComboBox.getSelectionModel().getSelectedItem();
        filteredData.setPredicate(item -> {
            boolean matchesLevel = "全部".equals(selectedLevel) || (item.getAqiLevel() != null && item.getAqiLevel().equals(selectedLevel));
            if (searchText == null || searchText.trim().isEmpty()) {
                return matchesLevel;
            } else {
                String lower = searchText.trim().toLowerCase();
                boolean matchesText = (item.getProvince() != null && item.getProvince().toLowerCase().contains(lower)) ||
                        (item.getCity() != null && item.getCity().toLowerCase().contains(lower)) ||
                        (item.getGridWorker() != null && item.getGridWorker().toLowerCase().contains(lower)) ||
                        (item.getReporter() != null && item.getReporter().toLowerCase().contains(lower));
                return matchesLevel && matchesText;
            }
        });
    }

    @FXML
    private void handleResetSearch() {
        searchField.clear();
        aqiLevelComboBox.getSelectionModel().selectFirst();
        filteredData.setPredicate(p -> true);
    }

    @FXML
    private void handleViewDetailsAndConfirm() {
        AQIData selected = aqiDataTable.getSelectionModel().getSelectedItem();
        if (selected == null) {
            Alert alert = new Alert(AlertType.WARNING);
            alert.setTitle("未选择数据");
            alert.setHeaderText(null);
            alert.setContentText("请先选择一行数据！");
            alert.showAndWait();
            return;
        }
        StringBuilder sb = new StringBuilder();
        sb.append("编号: ").append(selected.getId()).append("\n");
        sb.append("反馈者姓名: ").append(selected.getReporter()).append("\n");
        sb.append("所在省: ").append(selected.getProvince()).append("\n");
        sb.append("所在市: ").append(selected.getCity()).append("\n");
        sb.append("预估污染等级: ").append(selected.getAqiLevel()).append("\n");
        sb.append("反馈日期: ").append(selected.getDate()).append("\n");
        sb.append("反馈时间: ").append(selected.getTime()).append("\n");
        sb.append("网格员: ").append(selected.getGridWorker()).append("\n");
        Alert alert = new Alert(AlertType.INFORMATION);
        alert.setTitle("AQI数据详情");
        alert.setHeaderText("详细信息");
        alert.setContentText(sb.toString());
        alert.showAndWait();
    }

    @FXML
    private void handleRefreshData() {
        masterData.clear();
        masterData.addAll(service.getAllAQIData());
        filteredData.setPredicate(p -> true);
    }
}
